﻿const express = require('express')
const fs = require('fs')
const request = require('request')
const router = express.Router()
const path = require('path')

const PDFDocument = require('pdfkit');
const SVGtoPDF = require('svg-to-pdfkit');

const { getSvgHtml, delDir, productionPDfSVG } = require('./utils.js')



router.post('/pdf/pro', (req, res) => {
	//console.log(req.body)
	var obj = req.body;
	let arr = obj.arr, 
		info = obj.info, 
		mtoPt = 72/25.4,
		width = info.width * mtoPt,
		height = info.height * mtoPt,
		ratio = height / width,
		size = null;
		if (width > height) {
			if (width > 6000) {
				width =  6000;
				height = width * ratio;
			}
		} else {
			if (height > 6000) {
				height = 6000;
				width = height / ratio;
			}
		}
	size = [width, height];
	var doc = new PDFDocument({autoFirstPage: false, size});
	
	let opations = { preserveAspectRatio: 'none' }
	arr.forEach(item => {
		doc.addPage()
		SVGtoPDF(doc, item.svg, 0, 0, opations);
	})
	let title = path.resolve(`./public/pdf/${info.title}.pdf`);
	let stream = fs.createWriteStream(title);
	stream.on('finish', function() {
		// res.send(`http://localhost:5050/pdf/${info.title}.pdf`);
		res.download(title);
	})
	doc.pipe(stream);
	doc.end();
	
})

router.post('/pdf/download', (req, res) => {
	//console.log(req.body.arr)
	var obj = req.body;
	let arr = obj.arr.split(',,,'), 
		info = obj.info,
		mToPt = 72/25.4, 
		width = info.width * mToPt,
		height = info.height * mToPt,
		size = null;
		
	size = [width, height];
	
	fs.writeFile(path.resolve(`./data/data.txt`), arr, function(err) {
		if (err) console.log(err)
	})
	

	var doc = new PDFDocument({autoFirstPage: false, size});
	
	let opations = {assumePt: false, preserveAspectRatio: 'none' }
	arr.forEach(item => {
		doc.addPage()
		SVGtoPDF(doc, item, 0, 0, opations);
	})
	let title = path.resolve(`./public/pdf/${info.title}.pdf`);
	let stream = fs.createWriteStream(title);
	
	stream.on('finish', function() {
		console.log(title)
		// res.send(`http://localhost:5050/pdf/${info.title}.pdf`);
		 res.download(title);
		
	})
	doc.pipe(stream);
	doc.end();
	
})

/**
 * 后台服务端生成PDF专用
 * @parmas jsonPaths  json路径数组
 * @parmas width 宽度
 * @parmas height 高度
 * @parmas unit 单位
 * @parmas dpi
 */

var timer = null // 定时删除文件

router.post('/pdf/production', (req, res) => {
    var {jsonPaths, width, height, unit, dpi} = req.body

    if (!jsonPaths || !width || !height) { // 验证参数是否完整
        res.send({code: -1, msg: `缺少参数: jsonPaths: ${jsonPaths}, width: ${width}, height: ${height}`})
        return
    }
    try { // 转换json字符串
        jsonPaths = JSON.parse(jsonPaths)
    } catch {
        jsonPaths = []
    }
    // console.log(jsonPaths, width, height, unit, dpi)
    
    Promise.all(Array.from(jsonPaths).map(jp => {
        //请求json文件
        return new Promise((resolve, reject) => {
            request(jp, async function(err, response, body) {
                try {
                    body = JSON.parse(body)
                } catch {
                    body = []
                }
                var data = await getSvgHtml({page: body, width, height, unit, dpi})
                // var text = path.resolve(`./public/pdf/${new Date().getTime()}.svg`);
                // fs.writeFileSync(text, html);
                resolve(data)
            })
        }) 
    }))
    .then( svgs => { // 存储svg的字符串数组
        var mToPt = 72/25.4
        var size = [width * mToPt, height * mToPt]
        var doc = new PDFDocument({autoFirstPage: false, size});
        var opations = {assumePt: false, preserveAspectRatio: 'none' }
        var images = [] //存储需要删除的图片路径
        // fs.writeFileSync(path.resolve(`./public/pdf/${new Date().getTime()}.json`), JSON.stringify(data)) // 检查json
        svgs.forEach(item => { // 将svg转成PDF
            doc.addPage()
            SVGtoPDF(doc, item.html, 0, 0, opations);
            images = images.concat(images, item.images)
        })
        var name = new Date().toLocaleDateString() + '-' + new Date().getTime();
        var title = path.resolve(`./public/pdf/bg/${name}.pdf`);
        var stream = fs.createWriteStream(title);
        
        stream.on('finish', function() { //数据流pipe完成后,返回文件流
            res.download(title);
            clearTimeout(timer)
            timer = setTimeout(function() {
                delDir(path.resolve(`./public/pdf/bg`))
            }, 1000 * 60)
        })
        doc.pipe(stream);
        doc.end();
        
    })
    
})

/**
 * 使用滤镜后生成PDF的方法
 * @params {Arrary} pages 包含jsonContent的数组
 * @params {Object} info 模板信息
 */
router.post('/pdf/downPDF', async (req, res) => {
    // res.send(req.body)
    var pages = req.body.pages
    var info = req.body.info
    var mtoPt = 72/25.4
    var ptwidth = info.width * mtoPt
    var ptheight = info.height * mtoPt
    var ratio = info.height / info.width
    if (ptwidth > ptheight) {
        if (ptwidth > 6000) {
            ptwidth =  6000;
            ptheight = ptwidth * ratio;
        }
    } else {
        if (ptheight > 6000) {
            ptheight = 6000;
            ptwidth = ptheight / ratio;
        }
    }

    

    //开始创建PDF
    var doc = new PDFDocument({autoFirstPage: false, size: [ptwidth, ptheight]});

    let opations = { preserveAspectRatio: 'none' }
    var images = []
    for (var i = 0 ; i < pages.length; i++) {
         //等待处理完成svg
         var svgs = await productionPDfSVG({list: pages[i], info, ratio})
        //  console.log(svgs)

         doc.addPage()
         SVGtoPDF(doc, svgs.html, 0, 0, opations);
         images = images.concat(svgs.images)
    }
    let title = path.resolve(`./public/pdf/${info.title}.pdf`);
    let stream = fs.createWriteStream(title);
    stream.on('finish', function() {
        res.download(title, function(result) {
            for(var i = 0; i < images.length; i++) {
                var delPath = images[i]
                try {
                    /**
                     * @des 判断文件或文件夹是否存在
                     */
                    if (fs.existsSync(delPath)) {
                        fs.unlinkSync(delPath);
                    } else {
                        console.log('不存在 path：', delPath);
                    }
                } catch (error) {
                    console.log('del error', error);
                }
            }
            try {
                /**
                 * @des 判断文件或文件夹是否存在
                 */
                if (fs.existsSync(title)) {
                    fs.unlinkSync(title);
                } else {
                    console.log('不存在 path：', title);
                }
            } catch (error) {
                console.log('del error', error);
            }
        });
    })
    doc.pipe(stream);
    doc.end();

})


module.exports = router